package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //判断请求里是否带有blogId,有则单独处理
        String blogId = req.getParameter("blogId");
        String respJson = null ;
        if(blogId != null){
            //blogId不为空,说明是要拿到博客详情
           BlogDao blogDao = new BlogDao();
           Blog blog = blogDao.getBlog(Integer.parseInt(blogId));
            respJson = objectMapper.writeValueAsString(blog);

        }else{
            // 查询数据库, 拿到博客列表,然后转成json,返回到响应 ;
            BlogDao blogDao = new BlogDao();
            List<Blog> list = blogDao.getBlogs();
             respJson =  objectMapper.writeValueAsString(list);
        }
        System.out.println("respJson:"  + respJson);
        resp.setStatus(200);
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(respJson);
    }
}
